﻿using JT808.Gateway.Abstractions;
using JT808.Gateway.RabbitMQ.Configs;
using JT808.Protocol.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;

namespace JT808.Gateway.RabbitMQ
{
    public class JT808NotifyProducer : IJT808NotifyProducer
    {
        private bool disposed = false;
        public string TopicName { get; }
        IOptions<JT808NotifyProducerConfig> ProducerConfigAccessor;

        private IConnection Connection { get; set; }

        private IChannel Channel { get; set; }

        private readonly ILogger logger;

        public JT808NotifyProducer(ILoggerFactory loggerFactory,
          IOptions<JT808NotifyProducerConfig> producerConfigAccessor)
        {
            logger = loggerFactory.CreateLogger<JT808NotifyProducer>();
            TopicName = producerConfigAccessor.Value.ExchangeName;
            ProducerConfigAccessor = producerConfigAccessor;
        }
        private void Dispose(bool disposing)
        {
            if (disposed) return;
            if (disposing)
            {
                Channel.Dispose();
                Connection.Dispose();
            }
            disposed = true;
        }

        public void Dispose()
        {
            //必须为true
            Dispose(true);
            //通知垃圾回收机制不再调用终结器（析构器）
            GC.SuppressFinalize(this);
        }

        ~JT808NotifyProducer() { Dispose(false); }

        public async void ProduceAsync(string notifyKey, byte[] param)
        {
            if (disposed) return;
            try
            {
                if (Connection == null || Channel == null)
                {
                    Connection = await ProducerConfigAccessor.Value.ConnectionFactory.CreateConnectionAsync();
                    Channel = await Connection.CreateChannelAsync();
                    await Channel.ExchangeDeclareAsync(TopicName, ExchangeType.Fanout, durable: true);
                }
                await Channel.BasicPublishAsync(TopicName, notifyKey, param);
                logger.LogDebug($"A message has been produced with key={notifyKey} and value={param.ToHexString()}");
            }
            catch (AggregateException ex)
            {
                logger.LogError(ex, "rabbitmq error");
            }
        }
    }
}
